local limit_require = require "limit"
local utils = require "utils"
-- local cookie = require "resty.cookie":new()

-- cookie:set({
--     key = "city", 
--     value = "1",
--     path = "/",
--     domain = "example.com"
-- });

conf = {
    default_rule = {
        limiter = {}
    },
    probability_rule = {
        probability = {
            probability_rate = 10
        }
    },
    date_range_reject_rule = {
        date_range = {
            start_datetime = {year=2018, month=03, day=30, hour=0, min=0, sec=0},
            end_datetime = {year=2018, month=04, day=31, hour=0, min=0, sec=0}
            -- week_day = {3,4,6,7}
        },
        limiter = {}
    }
}

limit = limit_require:new(conf)

-- 在cookie找到限流目标，则全部限掉
function city_in_cookie_who(limit)

    local city, err = utils.get_cookie("city")
    if city ~= nil then
        return true, {rule="default_rule", message=echo_message}
    else
        return false
    end
end

-- 针对 GET 或者 POST 请求参数中如果有 city_num 的目标进行匹配
-- 在请求参数中找到限流目标，则限制50%概率
function city_in_args_who(limit)
    -- local redis = limit:get_redis()
    local args = limit.args
    local city_num = args["city_num"]
    -- city_num 25 江苏南京
    if city_num == "25" then
        return true, {rule = "probability_rule", message=echo_message, data={city="25"}}
    else 
        return false
    end
end

-- 针对时间范围目标匹配
-- 可以使用 http://www.somehost.com/some_location 来访问
-- 使用默认的 message 方法
function date_range_who(limit)
    return true, {rule = "date_range_reject_rule"}
end


-- 输出消息
function echo_message(limit, data)
    ngx.say("rejected anyway!")
    ngx.exit(ngx.HTTP_OK)
end

limit:who({city_in_cookie_who, city_in_args_who, date_range_who})
limit:execute()